package com.logjun.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.logjun.reggie.common.R;
import com.logjun.reggie.entity.Category;
import com.logjun.reggie.service.CategoryService;
import com.logjun.reggie.service.DishService;
import com.logjun.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RequestMapping("/category")
@RestController
@Slf4j
public class CategoryController {

    @Autowired
    CategoryService categoryService;

    /**
     菜品分类分页查询
     */
    @GetMapping("/page")
    @Cacheable(value = "categoryCache",key = "'categoryPage'+#page+'_'+#pageSize")
    public R page(int page,int pageSize){
        log.info("page = {},pageSize = {},name = {}" ,page,pageSize);
        //分页构造器
        Page<Category> pageInfo = new Page<>(page,pageSize);
        //条件构造器
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        //添加排序条件，根据sort进行排序
        queryWrapper.orderByAsc(Category::getSort);

        //分页查询
        categoryService.page(pageInfo,queryWrapper);
        return R.success(pageInfo);
    }

    /**
     * 新增菜品分类
     */
    @PostMapping
    @CacheEvict(value = "categoryCache",allEntries = true)
    public R save(@RequestBody Category category){
        log.info("新增菜品分类：{}",category.toString());
        categoryService.save(category);
        return R.success("新增菜品成功");
    }

    /**
     * 删除分类
     */
    @DeleteMapping
    @CacheEvict(value = "categoryCache",allEntries = true,beforeInvocation = false)
    public R<String> delete(Long ids){
        log.info("删除的分类id：{}",ids);
        //删除菜品分类之前，应先判断分类id是否关联dish表和setmeal表
        categoryService.remove(ids);
        return R.success("分类信息删除成功");

    }

    /**
     * 修改分类
     */
    @PutMapping
    @CacheEvict(value = "categoryCache",allEntries = true)
    public R<String> update(@RequestBody Category category){
        log.info("修改的分类信息：{}",category.toString());
        //
        categoryService.updateById(category);
        return R.success("分类信息更新成功");
    }

    /**
     * 根据条件查询菜品列表
     * @param type
     * @return
     */
    @GetMapping("/list")
    @Cacheable(value = "categoryCache",key = "'categoryList'+'_'+#type")
    public R list(Integer type){
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(type != null,Category::getType,type);
        //添加排序条件
        queryWrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
        List<Category> list = categoryService.list(queryWrapper);
        return R.success(list);
    }

}
